import { Component, Inject, Output, EventEmitter, OnInit } from '@angular/core';
import { MdDialog, MdDialogRef, MD_DIALOG_DATA } from '@angular/material';

import { User }                         from '../../../domain/user.mdl';
import { Hospital }                     from '../../../domain/hospital.mdl';
import { DlgMode, AuthorizationInfo }   from '../../../domain/definitions';

import { HospitalService }    from '../../../services/hospital.service';
import { UserService }        from '../../../services/user.service';

import { ListSelectDragula } from './list.select.dragula';

var DlgConfig = {
  disableClose:true,
  hasBackdrop:true,
  width:'640px',
  height:'480px'
};

@Component({
  selector: 'user-dialog-form',
  templateUrl: 'user.dialog.form.html',
  styles: [
    `.dlgheader {
      height:30px;
    }
    .dlgbody{
      width: 660px;
      height:400px;
    }
    .dlgfooter{
      height:30px;
    }
    .full-width {
      width: 100%;
    }
    .example-h2 {
      margin: 10px;
    }    
    .example-section {
      display: flex;
      align-content: center;
      align-items: center;
      height: 60px;
    }    
    .example-margin {
      margin: 0 10px;
    }
    .ml20{
      margin-left:20px;
    }
    .example-radio-group {
      display: inline-flex;
      flex-direction: row;
    }    
    .example-radio-button {
      margin: 5px;
    }    
    .example-selected-value {
      margin: 15px 0;
    }
    `
  ]
})
export class UserDialogForm implements OnInit {
 
  private errMsg: string;
  private hospitals:Hospital[];
  
  user: User;
  roles:any[] = [];
  dlgTitle:string = '添加管理员';
  authEcho:string ='';

  private dlgMode:DlgMode = DlgMode.Add;

  constructor(@Inject(MD_DIALOG_DATA) public data: any,
    public dialogRef: MdDialogRef<UserDialogForm>,
    private hospitalService: HospitalService,
    private userService:UserService,
    public dialog: MdDialog) {
      
    this.user = new User({name:'',email:''});
    for(let ai of AuthorizationInfo){
      this.roles.push(ai);
    }
    //console.log('roles=',JSON.stringify(this.roles,null,2));
    //console.log('UserDialogForm:constructor called.');
  }

  authedRes:Array<any>=[];
  unAuthedRes:Array<any>=[];
  
  updateAuthedHosInfo():void {
    this.hospitalService.getHospitals({role:'root'}).subscribe(
      hospitals =>{
        this.hospitals = hospitals;
        //console.log('hospitals.length=',this.hospitals.length);
        //console.log('calc authedRes and unAuthedRes...');
        if(this.hospitals && this.hospitals.length > 0) {
          var authedHids = [];
          if(this.user && this.user.hoslist.length > 0) {
            authedHids = [...this.user.hoslist];
          }

          this.authedRes = [];
          this.unAuthedRes = [];
          for(let hospital of this.hospitals) {
            var tmpObj = {
              name: hospital.name,
              value: hospital._id
            };
            if(authedHids.includes(hospital._id)) {
              this.authedRes.push(tmpObj);
            } else {
              this.unAuthedRes.push(tmpObj);
            }
          }
          //console.log('updateAuthedHosInfo over.');
        }        
      },
      error =>{
        layer.msg('load data failed.'+error);
      }
    );
  }

  ngOnInit(): void {
    if(this.data){
      this.dlgMode = DlgMode.Edit;
      this.user = this.data;
      this.dlgTitle = '修改管理员';
    }
    this.authEcho = '双击选择可管理的医院';
    if(this.user.role == 'root') {
      this.authEcho = '超级管理员可以管理所有医院';
    }
    this.updateAuthedHosInfo();
  }
  
  isDisabled():boolean{
    return this.dlgMode === DlgMode.Edit;
  }
  
  openListSelectDlg(dlgSize:string):void {
    var tmpA = dlgSize.split(',');
    var dlgSizeConf = {width:tmpA[0]+'px',height:tmpA[1]+'px'};
    var dataPkg = {selectedModel:[...this.authedRes],unSelectedModel:[...this.unAuthedRes]};
    let dialogRef = this.dialog.open(
      ListSelectDragula,$.extend({}, DlgConfig,dlgSizeConf,{data:dataPkg}));

    dialogRef.afterClosed().subscribe(result => {
      if(result != "" && Array.isArray(result)){
        var authedHids = [];
        result.forEach(function(item){
          //console.log(item.name,item.value);
          authedHids.push(item.value);
        });
        this.user.hoslist = authedHids;
        this.updateAuthedHosInfo();
      }      
    });
  }
  
  closeDlg():void {
    //this.dialogRef.close(this.hospital);
  }

  onSubmit():void {
    //console.log('onSubmit here.',JSON.stringify(this.user,null,2));
    //this.dialogRef.close(this.user);
    if(this.dlgMode == DlgMode.Add) {
      this.userService.addUser(this.user).subscribe(
        user => {
          this.user = user;
          //this.onUserAdded.emit(user);
          layer.msg('User add success.');
          this.dialogRef.close(this.user);          
        },
        error => {
          this.errMsg = <any>error;
          layer.msg('add failed.'+this.errMsg);
        }
      );
    }
    if(this.dlgMode == DlgMode.Edit){
      console.log('before update,user=',JSON.stringify(this.user,null,2));
      this.userService.updateUser(this.user).subscribe(
        user => {
          this.user = user;
          layer.msg('User update success.');
          this.dialogRef.close(this.user);
          console.log('after update,user=',JSON.stringify(this.user,null,2));
        },
        error =>{
          this.errMsg = <any>error;
          layer.msg('update failed.'+this.errMsg);
        }
      );
    }
  }
}
